package apis

import (
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"github.com/go-admin-team/go-admin-core/sdk/api"
	"github.com/go-admin-team/go-admin-core/sdk/pkg"
	"github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth/user"
	"gorm.io/gorm"
	"net/http"
	"strconv"
	"time"
	"tuowei.com/app/admin/models"
	"tuowei.com/app/admin/service"
	"tuowei.com/app/admin/service/dto"
	apimodels "tuowei.com/app/api/models"
	apiservice "tuowei.com/app/api/service"
	apidto "tuowei.com/app/api/service/dto"
	"tuowei.com/common/actions"
	"tuowei.com/pkg/xlog"
)

type SysOrder struct {
	api.Api
	Base
}

// AddOfflineOrder 新增线下订单
func (order SysOrder) AddOfflineOrder(ctx *gin.Context) {
	s := service.SysOrder{}
	req := dto.SysOfflineOrderAddRequest{}
	err := order.MakeContext(ctx).
		MakeOrm().
		Bind(&req, binding.Default(ctx.Request.Method, ctx.ContentType())).
		MakeService(&s.Service).Errors
	if err != nil {
		order.Error(http.StatusBadRequest, err, err.Error())
		return
	}
	xlog.Infof("SysOfflineOrderAddRequest:%+v", req)
	err, req.BuyerId = order.GetUser(&order.Api)
	if err != nil {
		xlog.Error(err)
		order.Error(401, err, err.Error())
		return
	}
	if req.BuyerId == 0 {
		order.Error(401, nil, "发生了什么???")
		return
	}
	if len(req.CourseId) < 1 {
		order.Error(http.StatusBadRequest, err, "CourseId 为空")
		return
	}
	//查询课程信息
	so := service.SysOfflineCourse{}
	so.Orm = s.Orm
	reqo := dto.SysOfflineCourseById{}
	reqo.Id = req.CourseId[0]
	for _, v := range s.GetOffLineOrderByStudentId(req.BuyerId) {
		if reqo.Id == v {
			order.Error(http.StatusBadRequest, err, "您已购买过此课程，请勿重复提交订单")
			return
		}
	}
	var data models.SysOfflineCourse
	//数据权限检查
	p := actions.GetPermissionFromContext(ctx)
	err = so.Get(&reqo, p, &data)
	if err != nil {
		order.Error(http.StatusUnprocessableEntity, err, err.Error())
		return
	}
	req.Price = data.Price

	// 设置创建人
	req.SetCreateBy(user.GetUserId(ctx), user.GetUserName(ctx))
	id, err := s.InsertOfflineOrder(&req)
	if err != nil {
		order.Logger.Error(err)
		order.Error(500, err, err.Error())
		return
	}
	id.OrderType = "OfflineOrder"
	//insert linkorder
	req1 := dto.SysLinkOrderAddRequest{}
	req1.OrderId = id.Id
	req1.OrderType = "OfflineOrder"
	req1.Status = 1
	req1.BuyerId = id.BuyerId
	req1.OrderNumber = id.OrderNumber
	_, err = s.InsertLinkOrder(&req1)
	if err != nil {
		order.Logger.Error(err)
		order.Error(500, err, err.Error())
		return
	}
	order.OK(id, "创建成功")
}

// AddMaterialOrder 新增资料订单
func (order SysOrder) AddMaterialOrder(ctx *gin.Context) {
	s := service.SysOrder{}
	req := dto.SysMaterialOrderAddRequest{}
	err := order.MakeContext(ctx).
		MakeOrm().
		Bind(&req, binding.Default(ctx.Request.Method, ctx.ContentType())).
		MakeService(&s.Service).Errors
	if err != nil {
		order.Error(http.StatusBadRequest, err, err.Error())
		return
	}
	if req.BuyerId == 0 {
		err, req.BuyerId = order.GetUser(&order.Api)
		if err != nil {
			xlog.Error(err)
			order.Error(401, err, err.Error())
			return
		}
	}
	xlog.Infof("AddMaterialOrder:%+v", req)
	if len(req.ShoppingCartId) > 0 {
		for _, sh := range req.ShoppingCartId {
			//购物车
			//数据权限检查
			ss := apiservice.SysShoppingCart{}
			ss.Orm = s.Orm
			reqs := apidto.SysShoppingCartGetReq{}
			reqs.Id = sh
			p := actions.GetPermissionFromContext(ctx)
			object := apimodels.SysShoppingCart{}
			err = ss.Get(&reqs, p, &object)
			if err != nil {
				order.Error(http.StatusUnprocessableEntity, err, "购物车id不存在查询失败")
				return
			}
			for i := 0; i < object.Num; i++ {
				req.MaterialId = append(req.MaterialId, object.MaterialOnlineId)
			}
		}
	}
	//查询课程
	if len(req.MaterialId) < 1 {
		order.Error(http.StatusBadRequest, err, "MaterialId 为空")
		return
	}
	count := 0.00
	postage := 0.00
	for _, materialId := range req.MaterialId {
		sm := service.SysMaterial{}
		sm.Orm = s.Orm
		reqm := dto.SysMaterialById{}
		reqm.Id = materialId
		var object models.SysMaterial
		//数据权限检查
		p := actions.GetPermissionFromContext(ctx)
		err = sm.Get(&reqm, p, &object)
		if err != nil {
			order.Error(http.StatusUnprocessableEntity, err, "查询失败")
			return
		}
		count = count + float64(object.Price)
		if float64(object.Postage) > postage {
			postage = float64(object.Postage)
		}

	}
	//订单价格包含邮费
	req.Price = count + postage
	req.Postage = postage
	// 设置创建人
	req.SetCreateBy(user.GetUserId(ctx), user.GetUserName(ctx))
	id, err := s.InsertMaterialOrder(&req)
	if err != nil {
		order.Logger.Error(err)
		order.Error(500, err, err.Error())
		return
	}
	id.OrderType = "MaterialOrder"
	//insert linkorder
	req1 := dto.SysLinkOrderAddRequest{}
	req1.OrderId = id.Id
	req1.OrderType = "MaterialOrder"
	req1.Status = 1
	req1.BuyerId = id.BuyerId
	req1.OrderNumber = id.OrderNumber
	_, err = s.InsertLinkOrder(&req1)
	if err != nil {
		order.Logger.Error(err)
		order.Error(500, err, err.Error())
		return
	}
	//更新学生订单数
	err = s.Orm.Table("sys_student").Where("id=?", req.BuyerId).Update("order_count", gorm.Expr("order_count+ ?", 1)).Error
	if err != nil {
		xlog.Errorf("db error: %s", err)
		return
	}
	//删除购物车
	for _, ids := range req.ShoppingCartId {
		ss := apiservice.SysShoppingCart{}
		ss.Orm = s.Orm
		ss.Log = s.Log
		req := apidto.SysShoppingCartDeleteReq{}
		req.Id = ids
		err = ss.Remove(&req)
		if err != nil {
			order.Logger.Error(err)
			order.Error(500, err, "")
			return
		}
	}
	order.OK(id, "创建成功")
}
func (order SysOrder) UpdateMaterialOrder(ctx *gin.Context) {
	s := service.SysOrder{}
	req := dto.UpdateMaterialOrderRequest{}
	err := order.MakeContext(ctx).
		MakeOrm().
		Bind(&req, binding.Default(ctx.Request.Method, ctx.ContentType())).
		MakeService(&s.Service).Errors
	if err != nil {
		order.Logger.Error(err)
		order.Error(http.StatusBadRequest, err, err.Error())
		return
	}
	//app端不传状态，后端设置
	req.Status = 5

	//数据权限检查
	p := actions.GetPermissionFromContext(ctx)
	model := new(models.MaterialOrder)
	if err = order.Orm.First(model, "order_number=?", req.GetOrderNumber()).Error; err != nil {
		order.Error(http.StatusBadRequest, err, err.Error())
		return
	}
	req.Generate(model)
	err = s.UpdateMaterialByModel(model, p)
	if err != nil {
		order.Error(http.StatusInternalServerError, err, err.Error())
		return
	}
	//更新linkorder
	err = s.Orm.Table("sys_link_order").Where("order_number=?", req.OrderNumber).Update("status", 5).Error
	if err != nil {
		xlog.Errorf("db error: %s", err)
		order.Error(http.StatusInternalServerError, err, err.Error())
		return
	}
	order.OK(model, "success")
}

func (order SysOrder) DelOrder(ctx *gin.Context) {
	s := service.SysOrder{}
	req := dto.DelOrderRequest{}
	err := order.MakeContext(ctx).
		MakeOrm().
		Bind(&req, binding.Default(ctx.Request.Method, ctx.ContentType())).
		MakeService(&s.Service).Errors
	if err != nil {
		order.Logger.Error(err)
		order.Error(http.StatusBadRequest, err, err.Error())
		return
	}
	for _, o := range req.OrderNumber {
		//更新linkorder
		err = s.Orm.Table("sys_link_order").Where("order_number=?", o).Update("deleted_at", time.Now().Local()).Error
		if err != nil {
			xlog.Errorf("db error: %s", err)
			order.Error(http.StatusInternalServerError, err, err.Error())
			return
		}
	}

	order.OK(req.OrderNumber, "success")
}
func (order SysOrder) UpdateMaterialOrderInternal(ctx *gin.Context, req dto.UpdateMaterialOrderRequest) {
	s := service.SysOrder{}
	err := order.MakeContext(ctx).
		MakeOrm().
		MakeService(&s.Service).Errors
	if err != nil {
		order.Logger.Error(err)
		order.Error(http.StatusBadRequest, err, err.Error())
		return
	}

	//数据权限检查
	p := actions.GetPermissionFromContext(ctx)
	model := new(models.MaterialOrder)
	if err = order.Orm.First(model, "order_number=?", req.GetOrderNumber()).Error; err != nil {
		order.Error(http.StatusBadRequest, err, err.Error())
		return
	}
	req.Generate(model)
	err = s.UpdateMaterialByModel(model, p)
	if err != nil {
		order.Error(http.StatusInternalServerError, err, err.Error())
		return
	}
	order.OK(model, "success")
}

func (order SysOrder) UpdateOnlineOrder(ctx *gin.Context) {
	s := service.SysOrder{}
	req := dto.UpdateOnlineOrderRequest{}
	err := order.MakeContext(ctx).
		MakeOrm().
		Bind(&req, binding.Default(ctx.Request.Method, ctx.ContentType())).
		MakeService(&s.Service).Errors
	if err != nil {
		order.Logger.Error(err)
		order.Error(http.StatusBadRequest, err, err.Error())
		return
	}
	//数据权限检查
	p := actions.GetPermissionFromContext(ctx)
	model := new(models.OnlineOrder)
	if err = order.Orm.First(model, "order_number=?", req.GetOrderNumber()).Error; err != nil {
		order.Error(http.StatusBadRequest, err, err.Error())
		return
	}
	req.Generate(model)
	err = s.UpdateOnlineByModel(model, p)
	if err != nil {
		order.Error(http.StatusInternalServerError, err, err.Error())
		return
	}
	order.OK(model, "success")
}
func (order SysOrder) UpdateOnlineOrderInternal(ctx *gin.Context, req dto.UpdateOnlineOrderRequest) {
	s := service.SysOrder{}
	err := order.MakeContext(ctx).
		MakeOrm().
		MakeService(&s.Service).Errors
	if err != nil {
		order.Logger.Error(err)
		order.Error(http.StatusBadRequest, err, err.Error())
		return
	}
	//数据权限检查
	p := actions.GetPermissionFromContext(ctx)
	model := new(models.OnlineOrder)
	if err = order.Orm.First(model, "order_number=?", req.GetOrderNumber()).Error; err != nil {
		order.Error(http.StatusBadRequest, err, err.Error())
		return
	}
	//xlog.Errorf("UpdateOnlineOrderRequest:", req)
	req.Generate(model)
	//xlog.Errorf("UpdateOnlineOrderRequest model:", model)
	err = s.UpdateOnlineByModel(model, p)
	if err != nil {
		order.Error(http.StatusInternalServerError, err, err.Error())
		return
	}
	order.OK(model, "success")
}

// AddOnlineOrder 新增在线订单
func (order SysOrder) AddOnlineOrder(ctx *gin.Context) {
	s := service.SysOrder{}
	req := dto.SysOnlineOrderAddRequest{}
	err := order.MakeContext(ctx).
		MakeOrm().
		Bind(&req, binding.Default(ctx.Request.Method, ctx.ContentType())).
		MakeService(&s.Service).Errors
	if err != nil {
		order.Error(http.StatusBadRequest, err, err.Error())
		return
	}
	xlog.Infof("AddOnlineOrder:%+v", req)
	if req.BuyerId == 0 {
		err, req.BuyerId = order.GetUser(&order.Api)
		if err != nil {
			xlog.Error(err)
			order.Error(401, err, err.Error())
			return
		}
	}
	//直接购买还是购物车购买
	if len(req.CourseId) > 0 {

	}
	if len(req.ShoppingCartId) > 0 {
		for _, sh := range req.ShoppingCartId {
			//购物车
			//数据权限检查
			ss := apiservice.SysShoppingCart{}
			ss.Orm = s.Orm
			ss.Log = s.Log
			reqs := apidto.SysShoppingCartGetReq{}
			reqs.Id = sh
			p := actions.GetPermissionFromContext(ctx)
			object := apimodels.SysShoppingCart{}
			err = ss.Get(&reqs, p, &object)
			if err != nil {
				order.Error(http.StatusUnprocessableEntity, err, "购物车id不存在查询失败")
				return
			}
			for i := 0; i < object.Num; i++ {
				req.CourseId = append(req.CourseId, object.MaterialOnlineId)
			}
		}
	}
	//查询课程
	if len(req.CourseId) < 1 {
		order.Error(http.StatusBadRequest, err, "CourseId 为空")
		return
	}
	for _, i := range req.CourseId {
		sc := service.SysCourse{}
		sc.Orm = s.Orm
		reqc := dto.SysCourseById{}
		reqc.Id = i
		var data models.SysCourse
		//数据权限检查
		p := actions.GetPermissionFromContext(ctx)
		err = sc.Get(&reqc, p, &data)
		if err != nil {
			order.Error(http.StatusUnprocessableEntity, err, "查询失败")
			return
		}
		req.IsBindOffline = data.IsBindOffline
		req.TeacherId = data.LecturerId
		req.Price = req.Price + data.Price
		req.CourseType = data.CourseType
	}

	// 设置创建人
	req.SetCreateBy(user.GetUserId(ctx), user.GetUserName(ctx))
	id, err := s.InsertOnlineOrder(&req)
	if err != nil {
		order.Logger.Error(err)
		order.Error(500, err, err.Error())
		return
	}
	//更新学生订单数
	err = s.Orm.Table("sys_student").Where("id=?", req.BuyerId).Update("order_count", gorm.Expr("order_count+ ?", 1)).Error
	if err != nil {
		xlog.Errorf("db error: %s", err)
		return
	}

	id.OrderType = "OnlineOrder"
	//insert linkorder
	req1 := dto.SysLinkOrderAddRequest{}
	req1.OrderId = id.Id
	req1.OrderType = "OnlineOrder"
	req1.Status = 1
	req1.BuyerId = id.BuyerId
	req1.OrderNumber = id.OrderNumber
	_, err = s.InsertLinkOrder(&req1)
	if err != nil {
		order.Logger.Error(err)
		order.Error(500, err, err.Error())
		return
	}
	//删除购物车
	for _, ids := range req.ShoppingCartId {
		ss := apiservice.SysShoppingCart{}
		ss.Orm = s.Orm
		req := apidto.SysShoppingCartDeleteReq{}
		req.Id = ids
		err = ss.Remove(&req)
		if err != nil {
			order.Logger.Error(err)
			order.Error(500, err, "")
			return
		}
	}
	order.OK(id, "创建成功")
}

type SysLearningListInsertReq struct {
	CourseId int    `json:"course_id" comment:"课程ID"`
	Name     string `json:"name" comment:"课程名称"`
	Subject  string `json:"subject" comment:"科目"`
	Cover    string `json:"cover" comment:"课程封面"`
	BuyerId  int    `json:"buyer_id" comment:"购买学员ID"`
}

// 商品计算
func (order SysOrder) OrderCount(ctx *gin.Context) {
	sMaterial := service.SysMaterial{}
	req := dto.OrderCountRequest{}
	err := order.MakeContext(ctx).MakeOrm().
		Bind(&req, binding.Default(ctx.Request.Method, ctx.ContentType())).
		MakeService(&sMaterial.Service).Errors
	if err != nil {
		order.Error(http.StatusBadRequest, err, err.Error())
		return
	}
	count := 0.00
	postage := 0.00
	for _, o := range req.OrderCountList {
		switch o.OrderType {
		case "MaterialOrder":
			req := dto.SysMaterialById{}
			req.Id = o.Id
			//数据权限检查
			p := actions.GetPermissionFromContext(ctx)

			detail := new(models.SysMaterial)
			detail.Id = o.Id
			err = sMaterial.Get(&req, p, detail)
			if err != nil {
				order.Error(500, err, "查询失败")
				return
			}
			count = count + float64(detail.Price)*float64(o.Num)
			if float64(detail.Postage) > postage {
				postage = float64(detail.Postage)
			}
		//case "OfflineOrder":
		//	s := service.SysOfflineCourse{}
		//	s.Orm = sMaterial.Orm
		//	req := dto.SysOfflineCourseById{}
		//	req.Id = o.Id
		//	//数据权限检查
		//	p := actions.GetPermissionFromContext(ctx)
		//	detail := models.SysOfflineCourse{}
		//	err = s.Get(&req, p, &detail)
		//	if err != nil {
		//		order.Error(500, err, "查询失败")
		//		return
		//	}
		//	count = count + detail.Price*float64(o.Num)
		case "OnlineOrder", "LiveOrder":
			s := service.SysCourse{}
			s.Orm = sMaterial.Orm
			req := dto.SysCourseById{}
			req.Id = o.Id
			//数据权限检查
			p := actions.GetPermissionFromContext(ctx)
			detail := new(models.SysCourse)
			err = s.Get(&req, p, detail)
			if err != nil {
				order.Error(500, err, "查询失败")
				return
			}
			count = count + detail.Price*float64(o.Num)
		}
	}
	type OrderCount struct {
		Count   float64 `json:"count"`
		Postage float64 `json:"postage"`
	}
	b := &OrderCount{
		Count:   count + postage,
		Postage: postage,
	}
	order.Logger.Errorf("OrderCount:%+v", b)
	order.OK(b, "查询成功")
}

// 立即购买
func (order SysOrder) BuyNow(ctx *gin.Context) {
	sMaterial := service.SysMaterial{}
	buyNowRequest := dto.BuyNowRequest{}
	err := order.MakeContext(ctx).MakeOrm().
		Bind(&buyNowRequest, binding.Default(ctx.Request.Method, ctx.ContentType())).
		MakeService(&sMaterial.Service).Errors
	if err != nil {
		order.Error(http.StatusBadRequest, err, err.Error())
		return
	}
	if buyNowRequest.BuyerId == 0 {
		err, buyNowRequest.BuyerId = order.GetUser(&order.Api)
		if err != nil {
			xlog.Error(err)
			order.Error(401, err, err.Error())
			return
		}
	}

	type BuyNowResp struct {
		Order      []interface{} `json:"order"`
		OrderCount float64       `json:"order_count"`
		Postage    float64       `json:"postage"`
	}
	resp := BuyNowResp{}
	for _, g := range buyNowRequest.Goods {
		switch g.OrderType {
		case "MaterialOrder":
			req := dto.SysMaterialById{}
			req.Id = g.Id
			//数据权限检查
			p := actions.GetPermissionFromContext(ctx)

			detail := new(models.SysMaterial)
			err = sMaterial.Get(&req, p, detail)
			if err != nil {
				order.Error(500, err, "查询失败")
				return
			}
			resp.Order = append(resp.Order, detail)
			resp.OrderCount = resp.OrderCount + float64(detail.Price)*float64(g.Num)
			if float64(detail.Postage) > resp.Postage {
				resp.Postage = float64(detail.Postage)
			}
		case "OfflineOrder":
			s := service.SysOfflineCourse{}
			s.Orm = sMaterial.Orm
			req := dto.SysOfflineCourseById{}
			req.Id = g.Id
			//数据权限检查
			p := actions.GetPermissionFromContext(ctx)
			detail := models.SysOfflineCourse{}
			err = s.Get(&req, p, &detail)
			if err != nil {
				order.Error(500, err, "查询失败")
				return
			}
			resp.Order = append(resp.Order, detail)
			resp.OrderCount = resp.OrderCount + detail.Price*float64(g.Num)
		case "OnlineOrder", "LiveOrder":
			s := service.SysCourse{}
			s.Orm = sMaterial.Orm
			req := dto.SysCourseById{}
			req.Id = g.Id
			//数据权限检查
			p := actions.GetPermissionFromContext(ctx)
			detail := new(models.SysCourse)
			err = s.Get(&req, p, detail)
			if err != nil {
				order.Error(500, err, "查询失败")
				return
			}
			resp.Order = append(resp.Order, detail)
			resp.OrderCount = resp.OrderCount + detail.Price*float64(g.Num)
		}
	}

	s := apiservice.SysAddress{}
	s.Orm = sMaterial.Orm
	req := apidto.SysAddressGetPageReq{}
	req.StudentId = buyNowRequest.BuyerId
	//数据权限检查
	p := actions.GetPermissionFromContext(ctx)
	list := make([]apimodels.SysAddress, 0)

	err = s.GetPage(&req, p, &list)
	if err != nil {
		order.Error(500, err, "查询失败")
		return
	}
	order.OK(resp, "查询成功")
}

type KuaiDi struct {
	Name string `json:"name"`
	Code string `json:"code"`
}

// 在线订单列表
func (order SysOrder) GetMyOrderListLink(ctx *gin.Context) {
	s := service.SysOrder{}
	req := dto.SysLinkOrderListRequest{}
	err := order.MakeContext(ctx).
		MakeOrm().
		Bind(&req, binding.Default(ctx.Request.Method, ctx.ContentType())).
		MakeService(&s.Service).
		Errors
	if err != nil {
		order.Error(500, err, err.Error())
		return
	}
	if req.BuyerId == 0 {
		err, req.BuyerId = order.GetUser(&order.Api)
		if err != nil {
			xlog.Error(err)
			order.Error(401, err, err.Error())
			return
		}
	}
	//分页查询
	//数据权限检查
	p := actions.GetPermissionFromContext(ctx)
	list := make([]models.LinkOrder, 0)
	var count int64

	err = s.GetLinkOrderList(&req, p, &list, &count)
	if err != nil {
		order.Error(500, err, "查询失败")
		return
	}
	respList := make([]interface{}, 0)
	for _, o := range list {
		switch o.OrderType {
		case "OnlineOrder", "LiveOrder":
			req1 := dto.SysOnlineOrderDetailRequest{}
			req1.Id = o.OrderId
			detail := new(models.OnlineOrder)
			detail.Id = o.OrderId
			detail.OrderType = o.OrderType
			err = s.GetOnlineOrderDetail(&req1, p, detail)
			if err != nil {
				xlog.Error(err)
				continue
			}
			if detail.SubjectRelation != nil {
				detail.Subject = detail.SubjectRelation.Name
			}

			OnlineCount := make(map[int]int)
			Online := make(map[int]*models.SysCourse)
			for _, c := range detail.Course {
				Online[c.CourseId] = c
				if value, ok := OnlineCount[c.CourseId]; ok {
					OnlineCount[c.CourseId] = value + 1
				} else {
					OnlineCount[c.CourseId] = 1
				}
			}
			for key, va := range OnlineCount {
				sysCourseCount := &models.SysCourseCount{}
				if value, ok := Online[key]; ok {
					sysCourseCount.Course = value
					sysCourseCount.Count = va
				}
				xlog.Infof("GetMyOrderListLink sysCourseCount:%+v", sysCourseCount)
				detail.CourseCount = append(detail.CourseCount, sysCourseCount)
			}
			respList = append(respList, detail)
		case "MaterialOrder":
			req2 := dto.SysMaterialOrderDetailRequest{}
			req2.Id = o.OrderId
			detail := new(models.MaterialOrder)
			detail.Id = o.OrderId
			detail.OrderType = o.OrderType
			err = s.GetMaterialOrderDetail(&req2, p, detail)
			if err != nil {
				xlog.Error(err)
				continue
			}
			if detail.SubjectRelation != nil {
				detail.Subject = detail.SubjectRelation.Name
			}
			MaterialCount := make(map[int]int)
			Material := make(map[int]*models.SysMaterial)
			for _, c := range detail.Material {
				Material[c.Id] = c
				if value, ok := MaterialCount[c.Id]; ok {
					MaterialCount[c.Id] = value + 1
				} else {
					MaterialCount[c.Id] = 1
				}
			}
			for key, va := range MaterialCount {
				sysMaterialCount := &models.SysMaterialCount{}
				if value, ok := Material[key]; ok {
					value.CourseType = "material"
					sysMaterialCount.Material = value
					sysMaterialCount.Count = va
				}
				xlog.Infof("GetMyOrderListLink sysMaterialCount:%+v", sysMaterialCount)
				detail.MaterialCount = append(detail.MaterialCount, sysMaterialCount)
			}
			comName1, ok := ComName.Load(detail.ExpressCompany)
			if ok {
				detail.ExpressCompanyName = comName1.(string)
			}
			respList = append(respList, detail)
		case "OfflineOrder":
			req2 := dto.SysOfflineOrderDetailRequest{}
			req2.Id = o.OrderId
			detail := new(models.OfflineOrder)
			detail.Id = o.OrderId
			detail.OrderType = o.OrderType
			err = s.GetOfflineOrderDetail(&req2, p, detail)
			if err != nil {
				xlog.Error(err)
				continue
			}
			if detail.Status == 4 {
				detail.Status = 5
			}
			if detail.SubjectRelation != nil {
				detail.Subject = detail.SubjectRelation.Name
			}
			if len(detail.Course) > 0 {
				sysOfflineCount := &models.SysOfflineCount{}
				detail.Course[0].CourseType = "offline"
				sysOfflineCount.OfflineCourse = detail.Course[0]
				sysOfflineCount.Count = 1
				detail.OfflineCount = append(detail.OfflineCount, sysOfflineCount)
				respList = append(respList, detail)
			}
		}

	}
	ctx.JSON(http.StatusOK, map[string]interface{}{
		"requestId": pkg.GenerateMsgIDFromContext(ctx),
		"code":      http.StatusOK,
		"msg":       "查询成功",
		"data": map[string]interface{}{
			"count":     count,
			"pageIndex": req.GetPageIndex(),
			"pageSize":  req.GetPageSize(),
			"list":      respList,
		},
	})
}

type bindSignFlowId struct {
	Id         int    `json:"id" binding:"required"`           //订单id
	SignFlowId string `json:"sign_flow_id" binding:"required"` //签署流程id
}

func (order SysOrder) BindSignFlowId(ctx *gin.Context) {
	req := bindSignFlowId{}
	err := order.MakeContext(ctx).MakeOrm().Bind(&req, binding.JSON).Errors
	if err != nil {
		xlog.Error(err)
		order.Error(http.StatusBadRequest, err, err.Error())
		return
	}
	obj := new(models.OfflineOrder)
	err = order.Orm.Table(models.OfflineOrder{}.TableName()).Where("id = ?", req.Id).Find(obj).Error
	if err != nil {
		order.Error(http.StatusInternalServerError, err, err.Error())
		return
	}
	// 更新signFlowId
	err = order.Orm.Table(models.OfflineOrder{}.TableName()).Where("id = ?", req.Id).Update("sign_flow_id", req.SignFlowId).Error
	if err != nil {
		order.Error(http.StatusInternalServerError, err, err.Error())
		return
	}
	order.OK(nil, "success")
}

//
////BindContract 绑定线下订单的合同编号和地址
//func (order SysOrder) BindContract(ctx *gin.Context) {
//	req := apidto.OrderBindContractRequest{}
//	err := order.MakeContext(ctx).
//		MakeOrm().
//		Bind(&req, binding.JSON).
//		Errors
//	if err != nil {
//		order.Error(http.StatusBadRequest, err, err.Error())
//		return
//	}
//	db, err := order.GetOrm()
//	if err != nil {
//		xlog.Error(err)
//		order.Error(http.StatusInternalServerError, err, "服务器异常")
//		return
//	}
//	// 获取线下订单
//	var obj models.OfflineOrder
//	obj.Id = req.Id
//	err = db.Preload("Customer").Find(&obj).Error
//	if err != nil {
//		xlog.Error(err)
//		order.Error(http.StatusInternalServerError, nil, "服务器异常")
//		return
//	}
//	if obj.Customer == nil || obj.Customer.Id == 0 {
//		order.Error(http.StatusInternalServerError, nil, "该订单异常")
//		return
//	}
//	if obj.Customer.Province == 0 {
//		order.Error(http.StatusInternalServerError, nil, "您暂为绑定省份,请先完善基础信息")
//		return
//	}
//	if obj.ContractNumber != "" {
//		xlog.Error(obj.ContractNumber)
//		order.Error(http.StatusInternalServerError, nil, "您已经签过字了")
//		return
//	}
//	n, err := models.Contract{}.GetMaxContractNumAndInsert(db, obj.Customer.Province, time.Now().Format("2006"))
//	if err != nil {
//		order.Error(http.StatusInternalServerError, err, err.Error())
//		return
//	}
//	// 更新订单合同等信息
//	err = db.Table(obj.TableName()).Where("id = ?", obj.Id).Updates(map[string]interface{}{
//		"contract_url":    req.Url,
//		"contract_number": fmt.Sprintf("%02d%s%05d", obj.Customer.Province, time.Now().Format("2006"), n),
//	}).Error
//	if err != nil {
//		order.Error(http.StatusInternalServerError, err, err.Error())
//		return
//	}
//	order.OK(nil, "success")
//}
func (order SysOrder) OfflineOrderDetail(ctx *gin.Context) {
	id, _ := strconv.Atoi(ctx.Param("id"))
	order.MakeContext(ctx).MakeOrm()
	detail := new(models.OfflineOrder)
	detail.Id = id
	order.Orm.First(detail)
	order.OK(detail, "success")

}
